//
//  TxMapHelper.swift
//  TencentMap
//
//  Created by 吴非 on 2022/5/18.
//

import UIKit
import QMapKit
import CoreLocation

typealias LocationBlockHandler = (NSDictionary?) -> Void


public class TxMapHelper: NSObject {
    
    public static let `defaultService` = TxMapHelper()
 
    private var apiKey: String = ""
    
    
    // 配置参数
    public func configure(key: String) {
        
        TxMapHelper.defaultService.apiKey = key
        
        QMapServices.shared().apiKey = TxMapHelper.defaultService.apiKey
        
        QMSSearchServices.shared().apiKey = TxMapHelper.defaultService.apiKey
        // 4.5.6最新版本才有 #
        // QMapServices.shared().setPrivacyAgreement(true)
        
    }
    
    static func isAuthorization(controller: UIViewController, completionHandler: @escaping (Bool) -> Void ) {
        /// 权限检查
        if CLLocationManager.authorizationStatus() != .denied {
            completionHandler(true)
        } else {
            
            let appName: String = Bundle .main.infoDictionary?[ "CFBundleDisplayName" ] as? String ?? ""
            
            let alert = UIAlertController.init(title: "无法获取您的位置信息", message: "请在iPhone的“设置-隐私-定位服务”选项中打开定位服务，并允许\(appName)使用定位服务。", preferredStyle: .alert)
            alert.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: { [weak controller](sender) in
                /// 强制返回
                // controller?.navigationController?.popViewController(animated: true)
            }))
            alert.addAction(UIAlertAction.init(title: "设置", style: .default, handler: { (sender) in
                if let appSettings = URL(string: UIApplication.openSettingsURLString) {
                    UIApplication.shared.open(appSettings, options: [:], completionHandler: nil)
                }
            }))
            controller.present(alert, animated: true, completion: nil)
        }
    }
    
    
    /// 获取模块名称
    fileprivate static var modelName: String {
        return NSStringFromClass(TxMapHelper.classForCoder()).shear_front(c: ".")
    }
    /// 模块类名获取
    fileprivate static var className: String {
        return NSStringFromClass(TxMapHelper.classForCoder()).shear_after(c: ".")
    }
    
    /// 获取资源包 & 特别说明 组件模块和资源包bundle名称需要对应
    fileprivate static var forBundle: Bundle? {
        let tpClass: AnyClass = TxMapHelper.classForCoder()
        // 生成名称带xx-xx framework 会变成下划线`_`而资源包不会
        let tpModelName = TxMapHelper.modelName.replacingOccurrences(of: "_", with: "-")
        let tpURL = Bundle(for: tpClass).url(forResource: tpModelName, withExtension: "bundle")
        if let bURL = tpURL {
            return Bundle(url: bURL)
        } else {
            return nil
        }
    }
    
    
}

/// 便捷加载图片
internal func bbImage(_ imageName: String) -> UIImage? {
    // 主工程有图片 & 优先加载主工程
    if let kImage = UIImage(named: imageName) {
        return kImage
    }
    // 加载子模块图片
    if #available(iOS 13.0, *) {
        return UIImage(named: imageName, in: TxMapHelper.forBundle, with: nil)?.withRenderingMode(.alwaysOriginal)
    } else {
        return UIImage(named: imageName, in: TxMapHelper.forBundle, compatibleWith: nil)?.withRenderingMode(.alwaysOriginal)
    }
}



/// 字符串扩展剪切方法
fileprivate extension String {
    
   
    /// 截取某个字符之前数据
    func shear_front(c: String) -> String {
        guard let r =  self.range(of: c) else { return "" }
        return String(self[self.startIndex ..< r.lowerBound])
    }
    /// 截取某个字符之后数据
    func shear_after(c: String) -> String {
        guard let r =  self.range(of: c) else { return "" }
        return String(self[r.upperBound ..< self.endIndex])
    }
    
}
